package com.luke.nio.channel;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 将内容写入到文件里面
 * @Descrtption FileChannel
 * @Author luke
 * @Date 2020/4/23
 **/
public class NioFileChannel01 {

    public static void main(String[] args) throws Exception {
        String str = "你好，Luke";
        String filePath = "E:\\netty\\a1.txt";
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);

        //通过FileOutputStream 获取 FileChannel
        FileChannel fileChannel = fileOutputStream.getChannel();

        //创建缓冲区 ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //数据写入 ByteBuffer
        byteBuffer.put(str.getBytes());

        //ByteBuffer读写翻转，能写多少就只能读取多少
        byteBuffer.flip();

        //读取缓冲区数据，写入到 FileChannel
        fileChannel.write(byteBuffer);

        //关闭流
        fileOutputStream.close();

    }

}
